package com.example.pufang.controller.front;

import com.example.common.CommonResult;
import com.example.pufang.pojo.Chat;
import com.example.pufang.pojo.User;
import com.example.pufang.service.ChatService;
import com.example.pufang.service.UserService;
import com.example.pufang.vo.ChatListVo;
import com.example.pufang.vo.ChatVo;
import com.example.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/front/chat")
@CrossOrigin
@Api(tags = "h5用户聊天接口")
public class ChatFrontController {

    @Autowired
    private UserService userService;

    @Autowired
    private ChatService chatService;

    @Autowired
    private TokenUtil tokenUtil;

    @Operation(summary = "发送消息")
    @PostMapping("/send")
    public CommonResult<Boolean> send(@RequestBody Chat chat, HttpServletRequest request) {

        User sender = userService.getUserByPhone(tokenUtil.getFrontUserPhone(request));

        chat.setSenderId(sender.getId());
        chat.setCreateTime(new Date());

        return CommonResult.success(chatService.save(chat));
    }

    @Operation(summary = "与某个用户的消息列表")
    @GetMapping("/getList")
    public CommonResult<List<ChatVo>> getList(Integer receiverId, HttpServletRequest request) {
        User sender = userService.getUserByPhone(tokenUtil.getFrontUserPhone(request));

        User receiver = userService.getById(receiverId);

        return CommonResult.success(chatService.getList(sender, receiver));
    }

    @Operation(summary = "当用户的所有聊天列表")
    @GetMapping("/getPageList")
    public CommonResult<List<ChatListVo>> getPageList(HttpServletRequest request) {

        User sender = userService.getUserByPhone(tokenUtil.getFrontUserPhone(request));

        return CommonResult.success(chatService.getPageList(sender));
    }


}
